package com.ttxs.gateway.config;

import com.ttxs.common.core.properties.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.stream.Collectors;

@Configuration
@Slf4j
public class GatewayConfig {
    @Resource
    private SecurityProperties securityProperties;
    /**
     * 前端测试需要跨域配置
     * @return
     */
    @Bean
    CorsWebFilter corsConfigurationSource() {
        if (log.isDebugEnabled()) {
            log.debug("allowedOrigins:{}", securityProperties.getAllowedOrigins());
            log.debug("whiteList:{}", securityProperties.getWhiteList());
            log.debug("excludes:{}", securityProperties.getExcludes());
        }
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(securityProperties.getAllowedOrigins());
        configuration.setAllowedMethods(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        //设置预检请求的缓存时间（秒），在这个时间段里，对于相同的跨域请求不会再预检了
        configuration.setMaxAge(1800L);
        configuration.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return new CorsWebFilter(source);
    }

    /**
     * 默认不注入，如果在gateway中直接调用其他微服务会报没有HttpMessageConverter异常
     * @param converters
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public HttpMessageConverters messageConverters(ObjectProvider<HttpMessageConverter<?>> converters) {
        return new HttpMessageConverters(converters.orderedStream().collect(Collectors.toList()));
    }
}
